package com.tianruan.dc.common.annotation;

import com.tianruan.dc.common.annotation.condition.ApiVersionCondition;
import com.tianruan.dc.common.exception.ApiVersionException;
import com.tianruan.dc.common.utils.ApiVersionUtil;
import lombok.SneakyThrows;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.util.Assert;
import org.springframework.web.servlet.mvc.condition.RequestCondition;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Method;
import java.util.Objects;

/**
 * @PS Api版本控制处理器
 */
public class ApiRequestMappingHandlerMapping extends RequestMappingHandlerMapping {

    @SneakyThrows
    @Override
    protected RequestCondition<?> getCustomTypeCondition(Class<?> handlerType) {
        // 扫描类上的 @ApiVersion
        ApiVersion apiVersion = AnnotationUtils.findAnnotation(handlerType, ApiVersion.class);
        return createRequestCondition(apiVersion);
    }

    @SneakyThrows
    @Override
    protected RequestCondition<?> getCustomMethodCondition(Method method) {
        // 扫描方法上的 @ApiVersion
        ApiVersion apiVersion = AnnotationUtils.findAnnotation(method, ApiVersion.class);
        return createRequestCondition(apiVersion);
    }

    private RequestCondition<ApiVersionCondition> createRequestCondition(ApiVersion apiVersion) throws ApiVersionException {
        if (Objects.isNull(apiVersion)) {
            return null;
        }
        String value = apiVersion.value();
        Assert.isTrue(ApiVersionUtil.compareVersion(value, "1") >= 0, "Api Version Must be greater than or equal to 1.0.0");
        return new ApiVersionCondition(value);
    }
}
